import SwiftUI
import Observation

@Observable
final class FoodStoreListModel {
    
    var foodStores: [FoodStoreItemModel] = []
    var isLoadingMore = false
    var hasMore: Bool {
        foodStores.count < totalFoodShopNum
    }
    
    @ObservationIgnored
    var pageNum = 1
    @ObservationIgnored
    private var totalFoodShopNum = 0

    func getFoodStoreList(searchContent: String?, type: FoodTypeItemRespModel?, longitude: String?, latitude: String?) async throws {
        pageNum = 1
        let target = API.shopList(name: searchContent,
                                  firstLevel: type?.parentId,
                                  secondLevel: type?.id,
                                  lon: longitude,
                                  lat: latitude,
                                  pageNum: pageNum,
                                  pageSize: 10)
    
        let model = try await NetworkManager.shared.request(target, responseType: FoodStoreListRespModel.self)
        self.foodStores = model.rows.map({ FoodStoreItemModel(respModel: $0) })
        self.totalFoodShopNum = model.total
        
    }
    
    func getMoreStoreList(searchContent: String?, type: FoodTypeItemRespModel?, longitude: String?, latitude: String?) async throws {
        guard hasMore else {
            throw FoodError.noMore
        }
        
        isLoadingMore = true
        pageNum += 1
        let target = API.shopList(name: searchContent,
                                  firstLevel: type?.parentId,
                                  secondLevel: type?.id,
                                  lon: longitude,
                                  lat: latitude,
                                  pageNum: pageNum,
                                  pageSize: 10)
        do {
            let model = try await NetworkManager.shared.request(target, responseType: FoodStoreListRespModel.self)
            let moreList = model.rows.map({ FoodStoreItemModel(respModel: $0) })
            self.foodStores.append(contentsOf: moreList)
            self.totalFoodShopNum = model.total
            isLoadingMore = false
        } catch {
            pageNum -= 1
            isLoadingMore = false
            throw error
        }
    }
}

